package system

import (
	"context"

	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteRoleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	menuModel model.SysMenuModel
	roleModel model.SysRoleModel
	userModel model.SysUserModel
}

func NewDeleteRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteRoleLogic {
	return &DeleteRoleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
		roleModel: model.NewSysRoleModel(svcCtx.Orm),
		userModel: model.NewSysUserModel(svcCtx.Orm),
	}
}

func (l *DeleteRoleLogic) DeleteRole(req *types.IdRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	err = auth.HasPermission(l.menuModel,l.ctx,"system:role:remove")
	if err != nil {
		return nil,errorx.Unauthorized
	}
	authinfo,err := auth.GetAuth(l.ctx)
	if err != nil {
		return nil,errorx.AuthNoFound
	}

	if isAdmin,_ := auth.IsAdmin(l.ctx); !isAdmin {
		err = l.userModel.ExistByRidUid(l.ctx,nil,req.Id,authinfo.UserId)
		if err != nil {
			return nil,errorx.AuthNoFound
		}
	}
	// 删除包括部门关联、权限关联
	err = l.roleModel.DelRole(l.ctx,nil,req.Id)
	if err != nil {
		return nil,errorx.SqlDeleteError
	}
	err = l.roleModel.DelRDByRid(l.ctx,nil,req.Id)
	if err != nil {
		return nil,errorx.SqlDeleteError
	}
	err = l.roleModel.DelRMByRid(l.ctx,nil,req.Id)
	if err != nil {
		return nil,errorx.SqlDeleteError
	}

	return &types.CommonResponse{
		Status: 200,
		Msg: "删除成功",
	},nil
}
